package com.cy.gameserver.controller;

import com.cy.gameserver.data.CommonResponse;
import com.cy.gameserver.service.SmsService;
import com.cy.gameserver.service.UserService;
import com.cy.gameserver.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by tiankai.qin on 18/2/28.
 */
@Controller
public class LoginCtrl {

    private static final Logger logger = LoggerFactory.getLogger(LoginCtrl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @RequestMapping("/login/code/get")
    @ResponseBody
    public String getCode(@RequestParam String tel) {
        String code = genCode();
        smsService.sendValidateCode(tel, code);
        userService.saveCodeCache(tel, code);
        return JsonUtil.toJSON(CommonResponse.commonSucc());
    }


    @RequestMapping("/login/code/validate")
    @ResponseBody
    public String validateCode(@RequestParam String tel, @RequestParam String code) {
        CommonResponse response = new CommonResponse();
        boolean isSucc = userService.validateCode(tel, code);
        if (isSucc) {
            String token = userService.genToken(tel, "");
            userService.saveToken(tel, token);
            response.setCode(200);
            response.setMsg("validate succ");
            response.setData(token);
            logger.info("");
        } else {
            response.setCode(500);
            response.setMsg("validate failed");
        }
        return JsonUtil.toJSON(response);
    }

    @RequestMapping("/logout")
    @ResponseBody
    public String logout(@RequestParam String token) {
        CommonResponse response = new CommonResponse();
        boolean isSucc = userService.removeToken(token);
        if (isSucc) {
            response.setCode(200);
            response.setMsg("logout succ");
            logger.info("");
        } else {
            response.setCode(500);
            response.setMsg("validate failed");
        }
        return JsonUtil.toJSON(response);
    }

    //随机生成6位数字用作验证码
    private String genCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

}
